package com.frame.auth.resource.security.handler;

import com.frame.common.core.util.ResponseUtils;
import com.frame.common.tools.result.ResultCode;
import com.frame.common.tools.result.ServiceResult;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 它负责启动未经过身份验证的用户的身份验证过程(当他们试图访问受保护的资源）
 *
 * @auther zhangwj
 * @date 2021/3/18 下午1:47
 */
public class GoAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse,
                         AuthenticationException e) throws IOException, ServletException {
        if (e instanceof InsufficientAuthenticationException) {
            ResponseUtils.writeJson(httpServletResponse, ServiceResult.getFailureResult(ResultCode.INSUFFICIENT_AUTHENTICATION_ERROR));
        } else {
            ResponseUtils.writeJson(httpServletResponse, ServiceResult.getFailureResult(ResultCode.CANNOT_ACCESS));
        }
    }
}
